<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="desc">
        <el-input
            v-model="queryParams.desc"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单类型" prop="orderableType" v-if="userStore.shopId == null">
        <el-select v-model="queryParams.orderableType" placeholder="请选择订单类型" clearable>
          <el-option
            v-for="dict in order_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单类型" prop="orderableType" v-if="userStore.userType === '2'">
        <el-select v-model="queryParams.orderableType" placeholder="请选择订单类型" clearable>
          <el-option
              label="场馆"
              value="Business"
          />
          <el-option
              label="团购套餐"
              value="GroupPackage"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="价格区间">
        <el-row>
          <el-col :span="11">
            <el-input-number v-model="queryParams.miniPayFee" :controls="false" placeholder="最小价格"></el-input-number>
          </el-col>
          <el-col :span="2">-</el-col>
          <el-col :span="11">
            <el-input-number v-model="queryParams.maxiPayFee" :controls="false" placeholder="最大价格"></el-input-number>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in ty_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pay:tyOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tyOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" width="300" align="center" prop="orderNumber" />
      <el-table-column label="用户" width="80" align="center" prop="userName" />
      <el-table-column label="商品名称" width="250" align="center" prop="desc" />
      <el-table-column label="订单时间" width="180" align="center" prop="createTime" />
      <el-table-column label="订单类型" width="100" align="center" prop="orderableType">
        <template #default="scope">
          <dict-tag :options="order_type" :value="scope.row.orderableType"/>
        </template>
      </el-table-column>
      <el-table-column label="支付费用"  width="100" align="center" prop="payFee" />
      <el-table-column label="支付编号" width="250" align="center" prop="payNumber" />

      <el-table-column label="订单状态" width="100" align="center" prop="status" fixed="right">
        <template #default="scope">
          <dict-tag :options="ty_order_status" :value="scope.row.status.toString()"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" v-if="scope.row.status === 6" @click="handleView(scope.row, scope.index)" v-hasPermi="['pay:tyEvaluation:query']">评价信息</el-button>
          <el-button link type="primary"
                     :class="{'but-disabled': (scope.row.status === 2)}"
                     icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['pay:tyOrder:remove']">删除</el-button>
          <el-button v-if="scope.row.payFee > 0" link type="primary"
                     :class="{'but-disabled': !(scope.row.status === 2)}"
                     icon="RemoveFilled" @click="handleRefundOrder(scope.row)" v-hasPermi="['pay:tyOrder:refundOrder']">退款</el-button>
          <el-button v-if="scope.row.payFee === 0" link type="primary"
                     :class="{'but-disabled': !(scope.row.status === 2)}"
                     icon="RemoveFilled" @click="handleCancelOrder(scope.row)" v-hasPermi="['pay:tyOrder:refundOrder']">取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单详情对话框 -->
    <el-dialog title="评价详情" v-model="open" width="700px" append-to-body>
      <el-form :model="evaluationForm" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="评价人：">{{ evaluationForm.userName }}</el-form-item>
            <el-form-item
                label="评价单号："
            >{{ evaluationForm.orderOn }} </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评价商品：">{{ evaluationForm.orderableName }}</el-form-item>
            <el-form-item label="评分：">{{ evaluationForm.rating }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容：">{{ evaluationForm.comment }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件："><image-preview :src-list="evaluationForm.fileLists" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TyOrder">
import {
  listTyOrder,
  getTyOrder,
  delTyOrder,
  addTyOrder,
  updateTyOrder,
  refundOrder,
  cancelOrder
} from "@/api/pay/tyOrder";
import { getTyEvaluation } from "@/api/pay/tyEvaluation";
import useUserStore from '@/store/modules/user'
import {watch,onBeforeUnmount,ref} from "vue";
const userStore = useUserStore()
const { proxy } = getCurrentInstance();
const { order_type, ty_order_status } = proxy.useDict('order_type', 'ty_order_status');

const tyOrderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  evaluationForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNumber: undefined,
    orderableType: undefined,
    payFee: undefined,
    payType: undefined,
    payNumber: undefined,
    status: undefined,
    userName: undefined,
    miniPayFee:undefined,
    maxiPayFee:undefined
  },
  rules: {
    updateTime: [
      { required: true, message: "更新时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules,evaluationForm } = toRefs(data);

/** 查询订单详情列表 */
function getList() {
  loading.value = true;
  listTyOrder(queryParams.value).then(response => {
    tyOrderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    orderNumber: undefined,
    uid: undefined,
    orderableId: undefined,
    orderableType: undefined,
    type: undefined,
    payFee: undefined,
    payType: undefined,
    payNumber: undefined,
    status: undefined,
    desc: undefined,
    reason: undefined,
    createTime: undefined,
    updateTime: undefined,
    deleted: undefined
  };
  proxy.resetForm("tyOrderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.miniPayFee = '';
  queryParams.value.maxiPayFee = '';
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 详细按钮操作 */
function handleView(row) {
  const _orderNo = row.orderNumber
  getTyEvaluation(_orderNo).then(response => {
    evaluationForm.value = response.data;
    open.value = true;
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单详情";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTyOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单详情";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tyOrderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTyOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTyOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除该数据项？').then(function() {
    return delTyOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

//退款按钮
function handleRefundOrder(row) {
  row.reason = '官方操作退款';
  proxy.$modal.confirm('是否确认退款？').then(function() {
    return refundOrder(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("退款成功，等待1-3分钟刷新列表");
  }).catch(() => {});
}

//取消按钮
function handleCancelOrder(row) {
  proxy.$modal.confirm('是否确认取消？').then(function() {
    return cancelOrder(row);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("取消成功");
  }).catch(() => {});
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('pay/tyOrder/export', {
    ...queryParams.value
  }, `tyOrder_${new Date().getTime()}.xlsx`)
}
const stopWatching = watch(() => userStore.cascaderKey, (v) => {
  getList();
}, { immediate: true });

onBeforeUnmount(() => {
  stopWatching();
});
</script>
